package DAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import Classes.Usuario;
import Nucleo.ConexaoBanco;

public class UsuarioDAO {
	
	private ConexaoBanco conn;
	
	public UsuarioDAO(){
		conn = new ConexaoBanco();
	}
	
	public void inserir( Usuario user ){
		String sql = "INSERT INTO `Usuarios` (nome,telefone,login,senha) values ( ? , ? , ? , ?) ";
		try {
			PreparedStatement stmt = conn.getConnection().prepareStatement(sql);
			stmt.setString(1, user.getNome() );
			stmt.setString(2, user.getTelefone() );
			stmt.setString(3, user.getLogin() );
			stmt.setString(4, user.getSenha() );
			stmt.execute();
			stmt.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<Usuario> getUsuarios(){
		String sql = "SELECT * FROM `Usuarios`";
		List<Usuario> lista = new ArrayList<Usuario>();
		
		try {
			PreparedStatement stmt = conn.getConnection().prepareStatement(sql);
			ResultSet rs = stmt.executeQuery();
						
			while(rs.next()) {
				Usuario user = new Usuario();	
				
				user.setId	( rs.getInt("idUsuario") );
				user.setNome( rs.getString("nome") );
				user.setTelefone( rs.getString("telefone") );
				user.setLogin( rs.getString("login") );
				user.setSenha( rs.getString("senha"));
				
				lista.add( user );
			}
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return lista;		
	}
	
	
	public Usuario autorizarUsuario( String login , String senha ){
		
		for (Usuario user : this.getUsuarios() ) {
			if ( user.getLogin().equals(login) && user.getSenha().equals(senha) ) {
				return user;
			}
		}
		return null;
	}

	public boolean deletar(int idUsuario) {
		String sql = "DELETE FROM `Usuarios` WHERE `idUsuario` = '"+ idUsuario+"'";
		
		try {
			Statement stmt = conn.getConnection().createStatement();
			int delete = stmt.executeUpdate(sql);
			if ( delete == 1) {
				return true;
			} else {
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
		
	}
}
